using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Data.Common;
using System.Collections;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.SqlClient;

namespace MONA.Modules.Marketing.BLL
{
    public partial class WorkItem
    {
        private static void AssignedToUser(DbTransaction transaction, int workitemID, int userID)
        {
            string spName = "p_SYSTEM_WorkItem_AssignedToUser";
            SqlDatabase db = (SqlDatabase)DatabaseFactory.CreateDatabase();
            SqlCommand dbCommand = (SqlCommand)db.GetStoredProcCommand(spName);

            db.AddInParameter(dbCommand, "@WorkItemID", SqlDbType.Int, workitemID);
            db.AddInParameter(dbCommand, "@UserID", SqlDbType.Int, userID);

            if (transaction != null)
                db.ExecuteNonQuery(dbCommand, transaction);
            else
                db.ExecuteNonQuery(dbCommand);
        }

        public static int DeleteBy_User(DbTransaction transaction, int workitemID)
        {
            string spName = "p_SYSTEM_WorkItemUser_DeleteBy_WorkItemID";
            SqlDatabase db = (SqlDatabase)DatabaseFactory.CreateDatabase();
            SqlCommand dbCommand = (SqlCommand)db.GetStoredProcCommand(spName);
            db.AddInParameter(dbCommand, "@WorkItemID", SqlDbType.Int, workitemID);
            return db.ExecuteNonQuery(dbCommand, transaction);

        }

        public static bool AssignedToUsers(int workitemID, ArrayList users)
        {
            bool returnValue;
            SqlDatabase db = (SqlDatabase)DatabaseFactory.CreateDatabase();
            using (SqlConnection connection = (SqlConnection)db.CreateConnection())
            {
                connection.Open();
                SqlTransaction transaction = connection.BeginTransaction();
                {
                    try
                    {
                        // Clear all role of user before insert new role.
                        DeleteBy_User(transaction, workitemID);

                        foreach (string user in users)
                        {
                            AssignedToUser(transaction, workitemID, Convert.ToInt32(user));
                        }
                        transaction.Commit();
                        returnValue = true;
                    }
                    catch
                    {
                        transaction.Rollback();
                        returnValue = false;
                    }
                    finally
                    {
                        connection.Close();
                    }
                }
            }
            return returnValue;
        }
    }
}
